<?php declare(strict_types=1);

namespace App\Api\V2\Controller\Merchant;

use App\Api\Controllers\BaseController;
use App\Models\CommonConfigs;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Services\Pay\GuoTonXinYi\Pay;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class BalanceController extends BaseController
{
    use ResponseTrait;

    public function queryLimit(Request $request): string
    {
        $mch_id = $request->input("mch_id");
        try {
            if (empty($mch_id)) {
                throw new \Exception("商户号参数不能为空");
            }
            $mch_ids = explode(",", $mch_id);
            $config = CommonConfigs::query()->where("config_id", "1234")->first();
            if (empty($config)) {
                throw new \Exception("配置不存在");
            }
            $companyRuleId = DB::table('company_rule')->where(['code' => 'gtxy'])->value('id');
            $result = [];
            foreach ($mch_ids as $mch_no) {
                $result = Pay::queryLimit($mch_no, $config->toArray());
                if ($result->getCode() == 2) {
                    continue;
                }
                /**
                 * company_code:"easypaya"
                 * company_rule_id:42
                 * end_date:"20250605"
                 * mch_id:"531000022263097"
                 * quota:151.18000000000006
                 * start_date:"20250520"
                 */
                $result[] = [
                    "company_code" => "gtxy",
                    "company_rule_id" => $companyRuleId,
                    "end_date" => date("Ymd", (int)$result->getData()["time"]),
                    "mch_id" => $mch_no,
                    "quota" => (string)$result->getData()["balanceTxamt"],
                    "start_date" => date("Ym01", (int)$result->getData()["time"]),
                ];
            }
            return $this->successResponse("ok", $result);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

}
